package http

import (
	"io/ioutil"
	"net/http"

	"strings"
)

func Get(url string,params map[string]string,successFn func(string),failFn func(error)) {
	s := "?";
	if strings.Index(url,"?")>0{
		s=""
	}
	//遍历map
	if(len(params)>0){
		url+=s
		for k, v := range params {
			url+="&"+k+"="+v
		}
	}

	resp, err := http.Get(url)
	if err != nil {
		// handle error
		failFn(err)
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		failFn(err)
		return
	}

	successFn(string(body))
}
func Post(url string,params map[string]string,successFn func(string),failFn func(error)) {
	s := "";

	//遍历map
	if(len(params)>0){
		i:=0
		for k, v := range params {
			if i==0{
				s+=k+"="+v
			}else{
				s+="&"+k+"="+v
			}
			i++
		}
	}

	resp, err := http.Post(url,"application/x-www-form-urlencoded",strings.NewReader(s))
	if err != nil {
		// handle error
		failFn(err)
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		failFn(err)
		return
	}

	successFn(string(body))
}